<template>
  <!-- 系统配置 -->
  <div class="app-container">
    <el-row>
      <el-col :span="8">
        <div class="mainbox-left">

          <div class="box-card">
            <div style="margin-bottom:16px" class="filter-container">
              <el-input
                v-model.trim="configGroupListQuery.dictName"
                maxlength="30"
                clearable
                class="filter-item limit"
                style="margin:0;"
                placeholder="请输入字典名称"
                @keyup.enter.native="handleConfigGroupFilter"
              />
              <el-button
                type="primary"
                style="margin-left: 10px;"
                icon="el-icon-search"
                class="filter-item limit"
                @click="handleConfigGroupFilter"
              >
                搜索
              </el-button>
            </div>
            <div>

              <el-button
                v-permission="['BASE_SYSCONFIG_ADD_BUTTON']"
                size="mini"
                style="margin-bottom: 16px;"
                class="filter-item"
                @click="addConfigGroup"
              >
                新增
              </el-button>
              <el-button
                v-permission="['BASE_SYSCONFIG_DEL_BUTTON']"
                type="danger"
                size="mini"
                style="margin-bottom: 16px;"
                class="filter-item"
                @click="deleteConfigGroup"
              >
                删除
              </el-button>
            </div>
            <el-table
              ref="tableLeft"
              v-loading="configGroupListLoading"
              :data="configGroupList"
              border
              highlight-current-row
              style="width: 100%;"
              :header-cell-style="{background:'#F2F2f2'}"
              @row-click="clickConfigGroup"
            >
              <template slot="empty">
                <p>{{ $store.getters.dataText }}</p>
              </template>
              <el-table-column
                align="center"
                type="index"
                width="70"
                label="序号"
                :index="table1_index"
              />
              <el-table-column
                align="center"
                prop="dictName"
                label="字典名称"
                show-overflow-tooltip
              />
              <el-table-column
                align="center"
                prop="dictCode"
                label="编码"
                show-overflow-tooltip
              />
            </el-table>
            <!-- 分页器 -->
            <dt-pagination
              v-show="configGroupTotal > 0"
              :total="configGroupTotal"
              :page.sync="configGroupListQuery.pageNo"
              :limit.sync="configGroupListQuery.pageSize"
              @pagination="initConfigGroup"
            />
          </div>
        </div>
        <dtDialog
          title="添加配置类型"
          :visible.sync="configGroupVisible"
          :is-loading="loading"
          destroy-on-close
          @closeDialog="resetConfigGroupTemp"
          @comfirmBtn="submitConfigGroup()"
        >
          <el-form
            ref="configGroupDataForm"
            slot="content"
            :rules="configGroupRules"
            :model="configGroupTemp"
            label-position="right"
            label-width="82px"
            style="width: 100%"
          >
            <el-form-item label="字典类型" prop="dictTypeName">
              <el-input v-model.trim="configGroupTemp.dictTypeName" disabled />
            </el-form-item>
            <el-form-item label="字典名称" prop="dictName">
              <el-input v-model.trim="configGroupTemp.dictName" maxlength="30" show-word-limit
                        class="limit" />
            </el-form-item>
            <el-form-item label="字典简称" prop="dictShortName">
              <el-input v-model.trim="configGroupTemp.dictShortName" maxlength="30" show-word-limit
                        class="limit" />
            </el-form-item>
            <el-form-item label="字典编码" prop="dictCode">
              <el-input v-model.trim="configGroupTemp.dictCode" maxlength="30" show-word-limit
                        class="limit" />
            </el-form-item>
            <el-form-item label="编码简写" prop="dictShortCode">
              <el-input v-model.trim="configGroupTemp.dictShortCode" maxlength="30" show-word-limit
                        class="limit" />
            </el-form-item>
            <el-form-item label="排序" prop="dictSort">
              <el-input v-model.trim="configGroupTemp.dictSort" maxlength="8" :oninput="initPositiveInteger()"
                        show-word-limit class="limit" />
            </el-form-item>
          </el-form>
        </dtDialog>
      </el-col>
      <el-col :span="16" style="padding-left: 0px">
        <div class="mainbox">
          <!-- 顶部操作 -->
          <div class="filter-container">
            <el-form ref="filterFormRef" :inline="true" :model="filterForm">
              <el-form-item label="名称" prop="configName">
                <el-input
                  v-model.trim="filterForm.configName"
                  class="filter-item limit"
                  maxlength="30"
                  clearable
                  placeholder="请输入内容"
                  @keyup.enter.native="handleFilter"
                />
              </el-form-item>
              <el-form-item label="属性编码" prop="configCode">
                <el-input
                  v-model.trim="filterForm.configCode"
                  class="filter-item limit"
                  maxlength="30"
                  clearable
                  placeholder="请输入内容"
                  @keyup.enter.native="handleFilter"
                />
              </el-form-item>
            </el-form>
            <div class="flex-1" />
            <el-button type="primary" @click="handleFilter">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </div>
          <!-- 表格 -->
          <div class="table-container table-fullscreen">
            <div class="table-opt-container">
              <el-button
                v-permission="['BASE_SYSCONFIG_ADDRIGHT_BUTTON']"
                type="primary"
                icon="el-icon-plus"
                class="filter-item"
                @click="addSysConfig"
              >新增
              </el-button>
              <div class="flex-1" />
              <dt-dialog-column :columns="columns" @queryTable="getList" />
            </div>
            <el-table
              ref="table"
              v-loading="sysConfigListLoading"
              border
              :data="sysConfigList"
              highlight-current-row
              style="width: 100%;"
              :header-cell-style="headerCellStyle"
            >
              <template slot="empty">
                <p>{{ $store.getters.dataText }}</p>
              </template>
              <el-table-column
                fixed="left"
                type="index"
                label="序号"
                width="70"
                :index="table_index"
              />
              <el-table-column
                v-if="columns[0].show"
                key="configName"
                prop="configName"
                min-width="100px"
                label="名称"
                show-overflow-tooltip
              />
              <el-table-column
                v-if="columns[1].show"
                key="configCode"
                prop="configCode"
                label="属性编码"
                show-overflow-tooltip
              />
              <el-table-column
                v-if="columns[2].show"
                key="configValue"
                prop="configValue"
                label="属性值"
                width="166px"
              >
                <template slot-scope="scope">
                  <el-popover trigger="hover" placement="top">
                    <p>{{ scope.row.configValue }}</p>
                    <div slot="reference" class="name-wrapper">
                      <!-- <el-tag size="medium"> {{ scope.row.configValue.length>9?scope.row.configValue.slice(0,9)+'...':scope.row.configValue }}</el-tag> -->
                      <el-tag size="medium"> {{ getConfigValue(scope.row.configValue) }}</el-tag>
                    </div>
                  </el-popover>
                </template>
              </el-table-column>

              <el-table-column
                v-if="columns[3].show"
                key="remark"
                prop="remark"
                label="备注"
                show-overflow-tooltip
              />
              <el-table-column
                :key="Math.random()"
                fixed="right"
                label="操作"
                width="144"
                class-name="small-padding fixed-width"
              >
                <template slot-scope="{ row }">
                  <el-button
                    v-permission="['BASE_SYSCONFIG_UPDATERIGHT_BUTTON']"
                    size="mini"
                    style="padding: 7px"
                    @click="editSysConfig(row)"
                  >
                    修改
                  </el-button>
                  <el-button
                    v-permission="['BASE_SYSCONFIG_DELRIGHT_BUTTON']"
                    size="mini"
                    type="danger"
                    @click="deleteSysConfig(row)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <!-- 分页器 -->
            <dt-pagination
              v-show="sysConfigListTotal > 0"
              :total="sysConfigListTotal"
              :page.sync="filterForm.pageNo"
              :limit.sync="filterForm.pageSize"
              @pagination="getList"
            />
          </div>
          <dtDialog
            :title="textMap[dialogStatus]"
            destroy-on-close
            :visible.sync="sysConfigVisible"
            :is-loading="loading"
            @closeDialog="resetSysConfigTemp"
            @comfirmBtn="dialogStatus === 'create' ? createData() : updateData()"
          >
            <el-form
              ref="sysConfigDataForm"
              slot="content"
              :rules="sysConfigRules"
              :model="sysConfigTemp"
              label-position="right"
              label-width="82px"
              style="width: 100%;overflow-x: auto;"
            >
              <el-form-item label="参数名称" prop="configName">
                <el-input v-model.trim="sysConfigTemp.configName" maxlength="30" show-word-limit
                          class="limit" />
              </el-form-item>
              <el-form-item label="属性编码" prop="configCode">
                <el-input v-model.trim="sysConfigTemp.configCode" maxlength="30" show-word-limit
                          class="limit" />
              </el-form-item>
              <el-form-item label="系统参数" prop="sysFlag">
                <el-switch
                  v-model="sysConfigTemp.sysFlag"
                  :active-value="'Y'"
                  :inactive-value="'N'"
                />
              </el-form-item>
              <el-form-item label="属性值" prop="configValue">
                <el-input v-model.trim="sysConfigTemp.configValue" maxlength="500" show-word-limit
                          class="limit" />
              </el-form-item>
              <el-form-item label="备注" prop="remark">
                <el-input v-model.trim="sysConfigTemp.remark" class="limit" maxlength="200"
                          show-word-limit type="textarea" />
              </el-form-item>
            </el-form>
          </dtDialog>
        </div>
      </el-col>
    </el-row>
  </div>
</template>
<script>
import dictApi from '@/framework/api/dict'
import dictTypeApi from '@/framework/api/dictType'
import sysConfigApi from '@/framework/api/sysConfig'
import dialogColumn from '@/framework/utils/mixins/dialogColumn'
import { positiveInteger } from '@/framework/utils/validate'

export default {
  name: 'BaseSysconfig',
  mixins: [dialogColumn],
  data() {
    return {
      loading: false,
      configGroupTotal: 1,
      configGroupListLength: 0,
      configGroupListQuery: {
        limit: 10000,
        dictName: '',
        pageNo: 1,
        pageSize: 10
      },
      // 列信息
      columns: [
        { prop: 'configName', label: '名称', show: true },
        { prop: 'configCode', label: '属性编码', show: true },
        { prop: 'configValue', label: '属性值', show: true },
        { prop: 'remark', label: '备注', show: true }
      ],
      configGroupList: [],
      sysConfigListLength: 0,
      configGroupListLoading: false,
      configGroupVisible: false,
      configGroupTemp: {
        dictCode: '',
        dictName: '',
        dictShortCode: '',
        dictShortName: '',
        dictSort: '',
        dictTypeCode: '',
        dictTypeId: '',
        dictTypeName: ''
      },
      configGroupRules: {
        dictTypeName: [
          { required: true, message: '请输入字典类型', trigger: 'change' }
        ],
        dictCode: [
          { required: true, message: '请输入字典编码', trigger: 'change' }
        ],
        dictName: [
          { required: true, message: '请输入字典名称', trigger: 'change' }
        ],
        dictSort: [
          { required: true, message: '请输入排序', trigger: 'change' }
        ]
      },
      selectedConfigGroup: {},
      filterForm: {
        configName: '',
        configCode: '',
        groupCode: '',
        pageNo: 1,
        pageSize: 10
      },
      sysConfigListLoading: false,
      sysConfigList: [],
      sysConfigListTotal: 0,
      dialogStatus: '',
      textMap: {
        update: '修改系统配置',
        create: '新增系统配置'
      },
      sysConfigTemp: {
        configCode: '',
        configName: '',
        configValue: '',
        groupCode: '',
        remark: '',
        sysFlag: 'Y'
      },
      sysConfigRules: {
        configName: [
          { required: true, message: '请输入参数名称', trigger: 'change' },
          { pattern: /^[^#@%&*¥$*]+$/, message: '不要输入特殊字符' }
        ],
        configCode: [
          { required: true, message: '请输入属性编码', trigger: 'change' }
          // { pattern: /^[A-Za-z0-9_]+$/, message: '请输入字母或数字' }
        ],
        sysFlag: [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        configValue: [
          { required: true, message: '请输入属性值', trigger: 'change' }
        ],
        remark: [{ required: false, pattern: /^[^#@%&*¥$*]+$/, message: '不要输入特殊字符' }]

      },
      sysConfigVisible: false,
      headerCellStyle: {
        backgroundColor: '#f2f2f2'
      }
    }
  },
  watch: {
    // configGroupList: function() {
    //   this.$nextTick(function() {
    //     this.$refs.table.setCurrentRow(this.configGroupList[0])
    //   })
    // },
    selectedConfigGroup(val, newval) {
      if (this.selectedConfigGroup) {
        this.filterForm.groupCode = this.selectedConfigGroup.dictCode
        this.getList()
      }
    }

  },
  mounted() {
    this.handleConfigGroupFilter()
  },
  methods: {
    // 校验排序规则
    initPositiveInteger(data) {
      return positiveInteger(data)
    },
    handleConfigGroupFilter() {
      this.configGroupListQuery.pageNo = 1
      this.initConfigGroup()
    },
    initConfigGroup() {
      this.configGroupListLoading = true
      dictApi.getConfigGroupPage(this.configGroupListQuery).then((res) => {
        this.configGroupList = res.data.rows
        this.configGroupListLength = res.data.rows.length
        this.selectedConfigGroup = this.configGroupList[0]
        this.configGroupListLoading = false
        this.configGroupTotal = res.data.totalRows
        this.$nextTick(() => {
          this.$refs.tableLeft.setCurrentRow(this.configGroupList[0])
        })
      })
    },
    clickConfigGroup(row, column, event) {
      this.selectedConfigGroup = row
    },
    addConfigGroup() {
      dictTypeApi.getConfigDictTypeDetail().then((res) => {
        this.configGroupTemp.dictTypeCode = res.data.dictTypeCode
        this.configGroupTemp.dictTypeId = res.data.dictTypeId
        this.configGroupTemp.dictTypeName = res.data.dictTypeName
      })
      this.configGroupVisible = true
      this.$nextTick(() => {
        this.$refs['configGroupDataForm'].clearValidate()
      })
    },
    resetConfigGroupTemp() {
      this.configGroupTemp = {
        dictCode: '',
        dictName: '',
        dictShortCode: '',
        dictShortName: '',
        dictSort: '',
        dictTypeCode: '',
        dictTypeId: '',
        dictTypeName: ''
      }
    },
    submitConfigGroup() {
      this.$refs['configGroupDataForm'].validate((valid) => {
        if (valid) {
          this.loading = true
          try {
            dictApi.add(this.configGroupTemp).then((res) => {
              this.initConfigGroup()
              this.configGroupVisible = false
              this.$dtMessage({
                title: '成功',
                message: '新增成功',
                type: 'success',
                duration: 2000
              })
            })
            this.loading = false
          } catch (error) {
            this.loading = false
          }
        }
      })
    },
    deleteConfigGroup() {
      this.$dtMessageBox({ title: '提示', message: `确定要删除“${this.selectedConfigGroup.dictName}”吗?`, type: 'warning' }).then(() => {
        dictApi.beforeDelete(this.selectedConfigGroup.dictCode).then((res) => {
          if (res.success) {
            dictApi.delete(this.selectedConfigGroup).then((resp) => {
              if (this.configGroupListLength === 1) {
                this.configGroupListQuery.pageNo--
              }
              this.initConfigGroup()
              this.$dtMessage({
                title: '成功',
                message: '删除成功',
                type: 'success',
                duration: 2000
              })
            })
          }
        })
      }).catch(() => {
        // 取消不做操作
      })
    },
    // 列表序号
    table_index(index) {
      return (this.filterForm.pageNo - 1) * this.filterForm.pageSize + index + 1
    },
    // 获取页面列表
    getList() {
      this.sysConfigListLoading = true
      sysConfigApi.fetchPage(this.filterForm).then((res) => {
        this.sysConfigList = res.data.rows
        this.sysConfigListLength = res.data.rows.length
        this.sysConfigListTotal = res.data.totalRows
        this.sysConfigListLoading = false
      })
    },
    // 搜索
    handleFilter() {
      this.filterForm.pageNo = 1
      this.getList()
    },
    // 重置
    handleReset() {
      this.$refs.filterFormRef.resetFields('filterForm')
      this.handleFilter()
    },
    // 关闭弹窗，清除校验缓存
    resetSysConfigTemp() {
      this.sysConfigTemp = {
        configCode: '',
        configName: '',
        configValue: '',
        groupCode: '',
        remark: '',
        sysFlag: 'Y'
      }
    },
    addSysConfig() {
      this.dialogStatus = 'create'
      this.sysConfigVisible = true
      this.$nextTick(() => {
        this.$refs['sysConfigDataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['sysConfigDataForm'].validate((valid) => {
        if (valid) {
          this.loading = true
          this.sysConfigTemp.groupCode = this.selectedConfigGroup.dictCode
          try {
            sysConfigApi.add(this.sysConfigTemp).then((res) => {
              this.getList()
              this.sysConfigVisible = false
              this.$dtMessage({
                title: '成功',
                message: '新增成功',
                type: 'success',
                duration: 2000
              })
            })
            this.loading = false
          } catch (error) {
            this.loading = false
          }
        }
      })
    },
    editSysConfig(row) {
      this.dialogStatus = 'update'
      sysConfigApi.detail(row.configId).then((res) => {
        this.sysConfigTemp = res.data
        this.sysConfigVisible = true
        this.$nextTick(() => {
          this.$refs['sysConfigDataForm'].clearValidate()
        })
      })
    },
    updateData() {
      this.$refs['sysConfigDataForm'].validate((valid) => {
        if (valid) {
          this.loading = true
          try {
            sysConfigApi.edit(this.sysConfigTemp).then((res) => {
              this.getList()
              this.sysConfigVisible = false
              this.$dtMessage({
                title: '成功',
                message: '修改成功',
                type: 'success',
                duration: 2000
              })
            })
            this.loading = false
          } catch (error) {
            this.loading = false
          }
        }
      })
    },
    deleteSysConfig(row) {
      this.$dtMessageBox({ title: '提示', message: `确定要删除“${row.configName}”吗?`, type: 'warning' }).then(() => {
        sysConfigApi.delete(row).then((res) => {
          this.getList()
          this.$dtMessage({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
        })
      }).catch(() => {
        // 取消不做操作
      })
    },
    table1_index(index) {
      return (this.configGroupListQuery.pageNo - 1) * this.configGroupListQuery.pageSize + index + 1
    },
    getConfigValue(configValue) {
      const pattern_Ch = new RegExp('[\u4E00-\u9FA5]')
      if (pattern_Ch.test(configValue)) {
        configValue = configValue.length > 9 ? `${configValue.slice(0, 9)}...` : configValue
        return configValue
      } else {
        configValue = configValue.length > 20 ? `${configValue.slice(0, 20)}...` : configValue
        return configValue
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.filter-container{
  display: flex;
& .el-form-item {
    margin-bottom: 10px;
}
}
.configlist .el-card {
  }
</style>
<style scoped>
 .el-popover{
   max-width: 100px;
  }
</style>
